import {
	createRouter,
	createWebHashHistory
} from 'vue-router'
import routes from './routes'
import store from '@/store'
import config from '@/config'
import {getToken,removeToken} from '@/utils/token'
import {checkAccess} from '@/utils'

const router = createRouter({
	history: createWebHashHistory(),
	routes
})

router.beforeEach((to,from,next)=>{
	let token=getToken()
	if(to.name!=config.loginRouteName){
		if(token){
			var user=store.state.app.user
			if(!user){
				removeToken()
				next({name:config.loginRouteName})
			}else if(checkAccess(to,user)){
				store.commit('addTab',to)
				next()
			}else{
				next('/403')
			}

		}else{
			next({name:config.loginRouteName})
		}
	}else{
		if(token){
			next({name:config.baseRouteName})
		}else{
			next()
		}
	}
})

export default router
